<?php

class Seo_SitemapController extends Zend_Controller_Action {
	
	public function indexAction() {
		$file = APPLICATION_ROOT_DIR . DS . "sitemap.xml";
		
		if(!file_exists($file)) {
			$this->view->items = null;
			return;
		}
		
		$items = Nimblecms_Seo_Sitemap::getItems($file);
		$this->view->items = $items;
		
		$this->view->content = file_get_contents($file);
		$this->view->lastmod = filemtime($file);
	}
	
	public function addAction() {
		$request = $this->getRequest();
		if ($request->isPost()) {
			$loc 		= $request->getPost('url');			
			$priority 	= $request->getPost('priority');
			$changefreq = $request->getPost('frequency');
			
			$item = new Nimblecms_Seo_Sitemap_Item($loc, $changefreq, $priority);
			$file = APPLICATION_ROOT_DIR . DS . 'sitemap.xml';
			Nimblecms_Seo_Sitemap::addToSitemap($file, $item);
			
			$this->_helper->getHelper('FlashMessenger')
					->addMessage($this->view->translate('Add success'));
			$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'seo_sitemap_add'));
		}
	}
	
	public function deleteAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->getHelper('viewRenderer')->setNoRender();
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$urls = $request->getPost('urls');
			
			if (count($urls) > 0) {
				$file  = APPLICATION_ROOT_DIR . DS . 'sitemap.xml';
				$items = Nimblecms_Seo_Sitemap::getItems($file);
				
				$decodedUrls = array();
				foreach ($urls as $url) {
					$decodedUrls[] = urldecode($url);
				}
				
				foreach ($items as $index => $item) {
					if (in_array($item->getLoc(), $decodedUrls)) {
						unset($items[$index]);
					}
				}
				
				Nimblecms_Seo_Sitemap::save($file, $items);
			}
			
			$this->_helper->getHelper('FlashMessenger')
				->addMessage($this->view->translate('Delete success'));
			$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'seo_sitemap_index'));
		}		
	}	
}